// shapes.ts
import Konva from 'konva';
import { KeyListener } from "../../utils/KeyListener";
import { TransformerManager } from "./TransformerManager";
import { Circle, type CircleConfig } from 'konva/lib/shapes/Circle';
import type { Shape } from 'konva/lib/Shape';


export class ShapesManager {
    private shapes: Shape<CircleConfig>[] = [];  // 存储所有创建的图形
    private selectedShapes: Shape<CircleConfig>[] = [];  // 存储当前选中的图形

    constructor(
        private layer: Konva.Layer,
        private stage: Konva.Stage,
        private transformerManager: TransformerManager,
        private ctrlKeyListener: KeyListener
    ) {
        this.stage.on('click', () => {
            transformerManager.clear();
            this.selectedShapes = [];
            layer.batchDraw();
        });
    }
    // 根据图形类型创建图形并绑定事件
    createShape(): void {
        for (let i = 0; i < 10; i++) {
            const circle = new Circle({
                x: 150,
                y: 150,
                radius: 50,
                fill: 'blue',
                stroke: 'black',
                strokeWidth: 2,
                draggable: true,
            });
            // 绑定事件
            this.bindEvents(circle);

            // 添加到图层并记录
            this.shapes.push(circle);
            this.layer.add(circle);
            this.layer.batchDraw();
        }// 绑定事件（比如点击事件）
    }
    private bindEvents(shape: Shape<CircleConfig>): void {
        shape.on("click", (e) => {
            e.cancelBubble = true;  // 防止事件冒泡
            if (this.ctrlKeyListener.isCtrlPressed()) {
                // Ctrl 多选逻辑
                if (this.selectedShapes.includes(shape)) {
                    this.selectedShapes = this.selectedShapes.filter(
                        (s) => s !== shape
                    );
                } else {
                    this.selectedShapes.push(shape);
                }
            } else {
                // 单选逻辑
                this.selectedShapes = [shape];
            }

            // 绑定 Transformer
            this.transformerManager.bindToShapes(this.selectedShapes);
            this.layer.batchDraw();
        });
    };
}
